package com.gxkj.projects.myshopx.services.impl;

import com.gxkj.common.exceptions.BusinessException;
import com.gxkj.common.exceptions.ValidateException;
import com.gxkj.common.utils.ImageUtil;
import com.gxkj.common.utils.ListPager;
import com.gxkj.common.utils.SystemGlobals;
import com.gxkj.common.utils.ValidatorUtil;
import com.gxkj.projects.myshopx.MyshopxConfig;
import com.gxkj.projects.myshopx.dao.GoodsAttrDaoImpl;
import com.gxkj.projects.myshopx.dao.GoodsDaoImpl;
import com.gxkj.projects.myshopx.dao.GoodsGalleryDaoImpl;
import com.gxkj.projects.myshopx.dao.LinkGoodsDaoImpl;
import com.gxkj.projects.myshopx.dtos.GalleryDto;
import com.gxkj.projects.myshopx.entitys.*;
import com.gxkj.projects.myshopx.enums.ErrorCodeEnum;
import com.gxkj.projects.myshopx.enums.GoodsImgType;
import com.gxkj.projects.myshopx.services.GoodsService;
import com.gxkj.projects.myshopx.utils.MyFileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Service
public class GoodsServiceImpl  implements GoodsService {

    Logger LOG = LoggerFactory.getLogger(GoodsServiceImpl.class);

    @Autowired
    private ValidatorUtil validatorUtil;

    @Autowired
    private  GoodsDaoImpl goodsDao;

    @Autowired
    private GoodsGalleryDaoImpl goodsGalleryDaoImpl;

    @Autowired
    private GoodsAttrDaoImpl goodsAttrDaoImpl;

    @Autowired
    private LinkGoodsDaoImpl linkGoodsDaoImpl;

    /**
     * 记录日志到admin_log表
     * @param user
     * @param entity
     * @param goodsImg
     * @param galleryDtoList
     * @throws ValidateException
     */
    public void doAddGoods(User user, Goods entity, MultipartFile goodsImg, List<GalleryDto> galleryDtoList, List<GoodsAttr> goodsAttrList, List<LinkGoods> linkGoodses) throws ValidateException, IOException {
        //验证货号，要求货号唯一
        String goodsSn = entity.getGoodsSn();
        if(StringUtils.isEmpty(goodsSn)){
            BusinessException businessException = new BusinessException(ErrorCodeEnum.BUSSINESS_ERROR.getCode(),"货号不能存在");
            throw businessException;
        }else {
            if(goodsDao.isExitByGoodsSn(entity.getId(),entity.getGoodsSn())){
                BusinessException businessException = new BusinessException(ErrorCodeEnum.BUSSINESS_ERROR.getCode(),"该货号已经存在");
                throw businessException;
            }
        }
        String imageSaveDir = MyshopxConfig.getGoodsImgUploadDir();
        Calendar calendar = Calendar.getInstance();
        int cruuentYear = calendar.get(Calendar.YEAR);
        //检测图片是否是支持的类型
        String  imgTargetPath = null;
        if(goodsImg != null && !goodsImg.isEmpty() ){
            if(!ImageUtil.check_img_type(goodsImg)){
                BusinessException businessException = new BusinessException(ErrorCodeEnum.PARAMS_ERROR.getCode(),"图片格式不是支持的类型");
                throw businessException;
            }

        }else {
            BusinessException businessException = new BusinessException(ErrorCodeEnum.PARAMS_ERROR.getCode(),"商品图片不能为空");
            throw businessException;
        }
        //检测新增相册图片的图片类型
        if(galleryDtoList != null && !galleryDtoList.isEmpty() ){
            MultipartFile uploadFile = null;
            for(GalleryDto item :  galleryDtoList){
                uploadFile  = item.getUploadFile();
                if(uploadFile != null && !uploadFile.isEmpty()){
                    if(!ImageUtil.check_img_type(uploadFile)){
                        BusinessException businessException = new BusinessException(ErrorCodeEnum.PARAMS_ERROR.getCode(),"新增图片格式不是支持的类型");
                        throw businessException;
                    }
                }
            }
        }

        entity.setGoodsImg(imgTargetPath);
        entity.setCreatedAt(calendar.getTime());
        entity.setUpdatedAt(calendar.getTime());
        entity.setIsDelete(0);
        entity.setGoodsImg("");
        if(entity.getGoodsWeight() == null){
            entity.setGoodsWeight(new BigDecimal("0"));
        }
        if(entity.getPromotePrice() == null){
            entity.setPromotePrice(new BigDecimal("0"));
        }
        validatorUtil.validate(entity,true);
        goodsDao.insert(entity);



        if(goodsImg != null && !goodsImg.isEmpty() ){
            imgTargetPath = imageSaveDir+"/"+cruuentYear+"/"+ MyFileUtils.generateImgName(goodsImg, GoodsImgType.G,entity.getId());
            entity.setGoodsImg(imgTargetPath);
            //将图片上传到本地文件夹
            MyFileUtils.upload2Loacl(goodsImg,imgTargetPath);
        }
        goodsDao.update(entity);
        if(galleryDtoList != null && !galleryDtoList.isEmpty() ){
//            MultipartFile uploadFile = null;
            for(GalleryDto item :  galleryDtoList){
                GoodsGallery goodsGallery = new GoodsGallery();
                goodsGallery.setCreatedAt(calendar.getTime());
                goodsGallery.setUpdatedAt(calendar.getTime());
                goodsGallery.setImgDesc(item.getImgDesc());
                goodsGallery.setGoodsId(entity.getId());
                goodsGallery.setImgUrl("");
                goodsGallery.setImgOriginal("");
                goodsGallery.setImgOriginal("");
                goodsGalleryDaoImpl.insert(goodsGallery);
                item.setGoodsGalleryId(goodsGallery.getId());
            }
        }
        //上传图集图片
        if(galleryDtoList != null && !galleryDtoList.isEmpty() ){
             MultipartFile uploadFile = null;
            for(GalleryDto item :  galleryDtoList){
                uploadFile = item.getUploadFile();
                if(uploadFile != null && !uploadFile.isEmpty() ){
                    imgTargetPath = imageSaveDir+"/"+cruuentYear+"/"+ MyFileUtils.generateImgName(uploadFile, GoodsImgType.P,entity.getId());
                    //将图片上传到本地文件夹
                    MyFileUtils.upload2Loacl(uploadFile,imgTargetPath);

                    GoodsGallery goodsGallery =  goodsGalleryDaoImpl.selectById(item.getGoodsGalleryId(),GoodsGallery.class);
                    goodsGallery.setImgUrl(imgTargetPath);
                    goodsGalleryDaoImpl.update(goodsGallery);
                }

            }
        }
        //商品属性
        if(goodsAttrList != null && !goodsAttrList.isEmpty()){
            for(GoodsAttr goodsAttr : goodsAttrList){
                goodsAttr.setGoodsId(entity.getId());
                goodsAttr.setCreatedAt(calendar.getTime());
                goodsAttr.setUpdatedAt(calendar.getTime());
                goodsAttrDaoImpl.insert(goodsAttr);
            }
        }
        //关联商品
        if(linkGoodses!= null && linkGoodses.size() >0){
            LinkGoods item = null;
            Map<String,Boolean> duplicateMap = new HashMap<>();
            LinkGoodsPK linkGoodsPK = null;
            for(int i=0;i<linkGoodses.size();i++){
                item = linkGoodses.get(i);
                linkGoodsPK = item.getLinkGoodsPK();
                linkGoodsPK.setGoodsId(entity.getId());
                duplicateMap.put(linkGoodsPK.getAdminId()+"_"+linkGoodsPK.getGoodsId()+"_"+linkGoodsPK.getLinkGoodsId(),true);

                item.setLinkGoodsPK(linkGoodsPK);
                linkGoodsDaoImpl.insert(item);
            }
        }
    }


    public void doUpdateGoods(User user, Goods entity, MultipartFile goodsImg, List<GalleryDto> galleryDtoList, List<GoodsAttr> goodsAttrList,List<String> delGalleryList, List<String> delGoodsAttrIdList) throws ValidateException {
        String goodsSn = entity.getGoodsSn();
        if(StringUtils.isEmpty(goodsSn)){
            BusinessException businessException = new BusinessException(ErrorCodeEnum.BUSSINESS_ERROR.getCode(),"货号不能存在");
            throw businessException;
        }else {
            if(goodsDao.isExitByGoodsSn(entity.getId(),entity.getGoodsSn())){
                BusinessException businessException = new BusinessException(ErrorCodeEnum.BUSSINESS_ERROR.getCode(),"该货号已经存在");
                throw businessException;
            }
        }
        Goods dbentity = this.getById(entity.getId());
        entity.setIsDelete(dbentity.getIsDelete());
        entity.setCreatedAt(dbentity.getCreatedAt());
        entity.setUpdatedAt(new Date());


        validatorUtil.validate(entity,true);
        if(goodsDao.isExitByGoodsSn(entity.getId(),entity.getGoodsSn())){
            BusinessException businessException = new BusinessException(ErrorCodeEnum.BUSSINESS_ERROR.getCode(),"该货号已经存在");
            throw businessException;
        }
        goodsDao.updateByMerge(entity);
    }


    public void doDeleteGoods(User user, String goodsId) {
        Goods dbentity = this.getById(goodsId);
        dbentity.setIsDelete(1);
        dbentity.setUpdatedAt(new Date());
        goodsDao.updateByMerge(dbentity);
    }


    public ListPager<Goods> doPageHQL(int pagenNo, int pageSize,Goods entity) {
        return goodsDao.doPageHQL( pagenNo, pageSize,entity);
    }

    public Goods getById(String id) {
        Goods dbentity = goodsDao.selectById(id,Goods.class);
        return dbentity;
    }

    public List<GoodsGallery> selectGoodsGalleryByGoodsId(String goodsId){
       return  goodsGalleryDaoImpl.selectGoodsGalleryByGoodsId(goodsId);
    }


    public List<GoodsAttr> selectGoodsAttrByGoodsId(String goodsId) {
        return goodsAttrDaoImpl.selectGoodsAttrByGoodsId( goodsId) ;
    }


    public void updateGoodsGallery(User user,String galleryId, String goods_imgDesc) {
        GoodsGallery item =   goodsGalleryDaoImpl.selectById(galleryId,GoodsGallery.class);
        item.setUpdatedAt(new Date());
        item.setImgDesc(goods_imgDesc);
        goodsGalleryDaoImpl.update(item);
    }


    public void dodelGoodsGallery(User user,String galleryId) {
        goodsGalleryDaoImpl.deleteById(galleryId,GoodsGallery.class);
    }

}
